package com.studyroom.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.studyroom.entity.SnackOrder;
import com.studyroom.entity.Snack;
import com.studyroom.entity.User;
import com.studyroom.entity.OrderItem;
import com.studyroom.mapper.SnackOrderMapper;
import com.studyroom.service.SnackOrderService;
import com.studyroom.service.SnackService;
import com.studyroom.service.UserService;
import com.studyroom.service.OrderItemService;
import com.studyroom.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.math.BigDecimal;
import java.util.List;

@Service
public class SnackOrderServiceImpl extends ServiceImpl<SnackOrderMapper, SnackOrder> implements SnackOrderService {

    @Autowired
    private UserService userService;
    
    @Autowired
    private SnackService snackService;
    
    @Autowired
    private OrderItemService orderItemService;


    // 生成订单编号
    private String generateOrderNo() {
        return "SO" + System.currentTimeMillis();
    }

    @Override
    @Transactional
    public void createOrder(String username, SnackOrder order) {
        // 1. 获取用户信息
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }

        // 2. 校验订单项
        if (order.getItems() == null || order.getItems().isEmpty()) {
            throw new ServiceException("订单项不能为空");
        }

        // 3. 校验配送信息
        if (order.getDeliveryLocation() == null || order.getDeliveryTime() == null) {
            throw new ServiceException("配送信息不能为空");
        }

        // 4. 检查所有零食是否可用并校验库存
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (OrderItem item : order.getItems()) {
            Snack snack = snackService.getById(item.getSnackId());
            if (snack == null || snack.getStatus() != 1) {
                throw new ServiceException("零食不可购买");
            }
            if (snack.getStock() < item.getQuantity()) {
                throw new ServiceException("库存不足");
            }
            
            // 计算小计金额和总金额
            item.setPrice(snack.getPrice());
            totalAmount = totalAmount.add(snack.getPrice().multiply(new BigDecimal(item.getQuantity())));
        }

        // 5. 创建订单
        order.setUserId(user.getId());
        order.setTotalAmount(totalAmount);
        order.setStatus(1);  // 设置为待支付
        order.setCreatedAt(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());
        
        save(order);

        // 6. 创建订单详情并扣减库存
        for (OrderItem item : order.getItems()) {
            // 设置订单ID和创建时间
            item.setOrderId(order.getId());
            item.setCreatedAt(LocalDateTime.now());
            orderItemService.save(item);
            
            // 扣减库存
            Snack snack = snackService.getById(item.getSnackId());
            snack.setStock(snack.getStock() - item.getQuantity());
            snackService.updateById(snack);
        }
    }

    @Override
    public Page<SnackOrder> getMyOrders(String username, Integer status, Page<SnackOrder> page) {
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        
        // 查询订单列表
        Page<SnackOrder> orderPage = baseMapper.getMyOrders(page, user.getId(), status);
        
        // 查询每个订单的详情
        for (SnackOrder order : orderPage.getRecords()) {
            List<OrderItem> items = orderItemService.getOrderItems(order.getId());
            order.setItems(items);
        }
        
        return orderPage;
    }

    @Override
    @Transactional
    public void cancelOrder(String username, Long orderId) {
        // 1. 获取用户信息
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }

        // 2. 获取订单信息
        SnackOrder order = getById(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }

        // 3. 验证是否是当前用户的订单
        if (!order.getUserId().equals(user.getId())) {
            throw new ServiceException("无权操作此订单");
        }

        // 4. 检查订单状态是否可取消
        if (order.getStatus() != 1) {
            throw new ServiceException("当前状态不可取消");
        }

        // 5. 取消订单
        order.setStatus(0);  // 设置为已取消
        order.setUpdatedAt(LocalDateTime.now());
        updateById(order);

        // 6. 恢复库存
        for (OrderItem item : order.getItems()) {
            Snack snack = snackService.getById(item.getSnackId());
            snack.setStock(snack.getStock() + item.getQuantity());
            snackService.updateById(snack);
        }
    }
} 